<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['生产管理']" marginBottom="10px" currentMenu="申请退料"></crumbs>
    <div class="form-body">
      <div class="cards-box">
        <a-card title="基本信息" :bordered="false">
          <a-form-model layout="vertical" ref="ruleForm1" :model="requistionForm" :rules="rules">
            <a-form-model-item label="工单编号" required prop="orderId">
              <a-input
                @click="openIt"
                v-model="requistionForm.orderCode"
                placeholder="请选择"
                :read-only="true"
                :class="requistionForm.orderCode ? 'has-value' : ''"
              >
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                <a-icon
                  slot="suffix"
                  type="close-circle"
                  theme="filled"
                  class="close-icon"
                  @click="getSelectValue(false, '', [])"
                />
              </a-input>
            </a-form-model-item>
            <a-form-model-item label="生产产品">
              <a-input placeholder="-" disabled v-model="requistionForm.goodsName" />
            </a-form-model-item>
            <a-form-model-item />
          </a-form-model>
          <a-form-model layout="vertical" ref="ruleForm2" :model="requistionForm" :rules="rules">
            <a-form-model-item label="退料人" required prop="return">
              <j-select-user-by-dep
                @changeRow="userFilter"
                v-model="requistionForm.return"
                :seldep="true"
                :modalWidth="1000"
                :multi="false"
              ></j-select-user-by-dep>
            </a-form-model-item>
            <a-form-model-item label="基本单位">
              <a-input placeholder="-" disabled v-model="requistionForm.goodsBasicUnitText" />
            </a-form-model-item>
            <a-form-model-item />
          </a-form-model>
          <a-form-model layout="vertical" ref="ruleForm" :model="requistionForm" :rules="rules">
            <a-form-model-item label="退料时间">
              <a-date-picker
                format="YYYY-MM-DD HH:mm"
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                style="width: 100%"
                @change="changeDate"
              />
            </a-form-model-item>
            <a-form-model-item />
            <a-form-model-item />
          </a-form-model>
          <a-form-model layout="vertical">
            <a-form-model-item label="退料原因" style="width: 65%">
              <a-textarea placeholder="请输入" :maxLength="500" v-model="requistionForm.reason" />
            </a-form-model-item>
          </a-form-model>
        </a-card>
        <a-card title="退用物料" :bordered="false" style="margin-top: 12px">
          <j-editable-table
            ref="materialTable"
            :loading="goodsTable.loading"
            :columns="goodsTable.columns"
            :dataSource="goodsTable.dataSource"
            :maxHeight="300"
            :rowNumber="false"
            :actionButton="false"
            :rowSelection="true"
            :addActionButton="false"
            @valueChange="valueChange"
            @selectRowChange="selectRowChange"
          >
            <template v-slot:totalReceivedRemedyNum="props">
              {{ numFormat(props.value) }}
            </template>
            <template v-slot:returnNum="props">
              {{ numFormat(props.value) }}
            </template>
            <template v-slot:lockNum="props">
              {{ numFormat(props.value) }}
            </template>
            <template v-slot:action="props">
              <a-popconfirm title="是否删除?" ok-text="是" cancel-text="否" @confirm="handleDeleteGood(props)">
                <span class="del-text">删除</span>
              </a-popconfirm>
            </template>
            <template v-slot:num="props">
              <a-input :maxLength="20" v-model="props.value" placeholder="请输入" @input="(e) => inputNum(e, props)"></a-input>
            </template>
          </j-editable-table>
        </a-card>
        <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
          <a-form-model layout="vertical">
            <a-form-model-item label="备注" style="flex: 1">
              <a-textarea placeholder="请输入" :maxLength="500" v-model="requistionForm.remark" />
            </a-form-model-item>
          </a-form-model>
          <a-form-model layout="vertical">
            <a-form-model-item label="附件" style="flex: 1">
              <file-upload :ids="requistionForm.attachment" @getFileList="getFileList"></file-upload>
              <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
            </a-form-model-item>
          </a-form-model>
        </a-card>
        <div style="margin-top: 12px">
          <Examine @submitProcess="submitProcess" type="0" id="MESS_RETURN_MATERIAL_APPLY" ref="examine" />
          <div style="height: 50px"></div>
        </div>
      </div>
    </div>

    <div class="footer-submit form-footer">
      <a-button type="primary" @click="submitProcess" :loading="submitLoading"> 提交 </a-button>
    </div>
    <tableSelect ref="tableSelect" @getSelectValue="getSelectValue" :key="indexNumber">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
            <a-form-model-item label="工单编号">
              <a-input v-model="filterForm.orderCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="产品名称">
              <a-input v-model="filterForm.goodsName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchNumber()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetNumber">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { returnMaterialAdd } from '@/api/goodsManagement'
import moment from 'dayjs'
import { integerNum, validateDuplicateValue, commafyTofixed, fourFloatNum, numFormat } from '@/utils/util'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { productOrderList } from '@/api/productOrder'
import tableSelect from '@/components/tableSelect'
import Examine from '@/components/examine'
export default {
  data() {
    return {
      jkeForm: {
        title: '申请退料',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      //下拉改弹窗
      indexNumber: 0,
      columns: [
        {
          title: '工单编号',
          ellipsis: true,
          width: 180,
          dataIndex: 'orderCode',
        },
        {
          title: '产品名称',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsName',
        },
        {
          title: '规格',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsSpec',
        },
        {
          title: '基本单位',
          dataIndex: 'goodsBasicUnitText',
          ellipsis: true,
          width: 90,
        },
        {
          title: '负责人',
          dataIndex: 'principalName',
          width: 100,
          ellipsis: true,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 180,
          ellipsis: true,
        },
      ],
      numberValue: '',
      numberText: '',
      filterForm: {
        orderCode: '', //工单编号
        goodsName: '', //产品名称
      },
      //下拉改弹窗结束
      numFormat,
      disabled: false,
      moment,
      validateDuplicateValue,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      queryId: '',
      requistionForm: {
        attachment: '',
        returnerId: '',
        orderCode: '',
        orderId: '',
        goodsName: '',
        goodsBasicUnitText: '',
      },
      submitLoading: false, // 提交loading
      orderList: [],
      rules: {
        orderId: [{ required: true, message: '工单编号必填', trigger: 'change' }],
        return: [{ required: true, message: '退料人必填', trigger: 'change' }],
      },
      goodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '',
            width: '0%',
            key: 'goodsId',
            type: FormTypes.normal,
            visible: false,
          },
          {
            title: '',
            width: '0%',
            key: 'planId',
            type: FormTypes.normal,
          },
          {
            title: '物料',
            width: '10%',
            key: 'goodsName',
            type: FormTypes.normal,
          },
          {
            title: '规格',
            width: '10%',
            align: 'center',
            key: 'goodsSpec',
            type: FormTypes.normal,
          },
          {
            title: '物料类型',
            width: '10%',
            key: 'goodsTypeText',
            type: FormTypes.normal,
          },
          {
            title: '基本单位',
            width: '10%',
            key: 'goodsBasicUnitText',
            type: FormTypes.normal,
          },
          {
            title: '总领补量',
            width: '10%',
            key: 'totalReceivedRemedyNum',
            type: FormTypes.slot,
            slotName: 'totalReceivedRemedyNum',
          },
          {
            title: '已退量',
            width: '10%',
            key: 'returnNum',
            type: FormTypes.slot,
            slotName: 'returnNum',
          },
          {
            title: '在申退量',
            key: 'lockNum',
            width: '10%',
            type: FormTypes.slot,
            slotName: 'lockNum',
          },
          {
            title: 'canNum',
            key: 'canNum',
            type: FormTypes.hidden,
          },
          // {
          //   title: '本次退料量',
          //   width: '15%',
          //   key: 'num',
          //   type:  FormTypes.input,
          //   // isrequired: true,
          //   placeholder: '请输入${title}',
          //   defaultValue: '',
          //   validateRules: [
          //     {
          //       required: true, // 必填
          //       message: '${title}不能为空', // 提示的文本
          //     },
          //     { pattern: /^(([0-9]+)|([0-9]+\.[0-9]{0,4}))$/, message: '请输入零以上的数字（最多保留4位小数）' },
          //   ],
          // },
          {
            title: '本次退料量',
            width: '15%',
            key: 'num',
            type: FormTypes.slot,
            isrequired: true,
            placeholder: '请输入${title}',
            slotName: 'num',
            defaultValue: '',
            validateRules: [
              {
                pattern: /[1-9]+[0-9]*/,
                message: '${title}必须大于0',
              },
              {
                required: true,
                message: '${title}必须大于0',
              },
            ],
          },
          {
            title: '操作',
            width: '10%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      selectRowKeys: [],
    }
  },
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    Examine,
    tableSelect,
  },
  methods: {
    // 编号下拉改弹窗
    openIt() {
      let par = {
        list: '/mess/messProductOrder/list?statusListStr=notStarted,inProduction',
        visible: true, //弹窗开启
        title: '编号', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.numberValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.numberText, //回显的中文，如：'张三'
        textKey: 'orderCode', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    getSelectValue(id, text, item) {
      if (!id) {
        console.log('giao')
        this.requistionForm.goodsBasicUnitText = ''
        this.requistionForm.orderCode = ''
        this.requistionForm.goodsName = ''
        this.requistionForm.orderId = ''
        this.numberText = ''
        this.numberValue = ''
        this.goodsTable.dataSource = []
        return
      }
      this.indexNumber += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.numberValue = id
      this.numberText = text
      this.selectOrder(id)
    },
    searchResetNumber() {
      this.filterForm.orderCode = ''
      this.filterForm.goodsName = ''
      this.$refs.tableSelect.searchReset()
    },
    searchNumber() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    inputNum(e, props) {
      let newNum = fourFloatNum(e.target.value)
      let { values } = this.$refs.materialTable.getValuesSync({ validate: true, rowIds: [props.rowId] })
      let { canNum, totalReceivedRemedyNum, lockNum, returnNum } = values[0]
      // let quantity = Number(totalReceivedRemedyNum) - Number(returnNum) - Number(lockNum)
      if (Number(newNum) > canNum) {
        newNum = canNum
        this.$refs.materialTable.setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              // 在这里 values 中的 amount 是你 columns 中配置的 key
              num: newNum,
            },
          },
        ])
        this.$antdMessage.error('本次退料量不能大于可退还数量！可退还数量=总领补量-已退量-在申退量。')
        return
      }
      this.$refs.materialTable.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 amount 是你 columns 中配置的 key
            num: newNum,
          },
        },
      ])
    },
    handleDeleteGood(props) {
      this.$refs.materialTable.removeRows(props.rowId)
    },
    changeDate(v) {
      this.requistionForm.returnTime = moment(v).format('YYYY-MM-DD HH:mm:ss')
    },
    selectRowChange(ids) {
      this.selectRowKeys = ids
    },
    valueChange(type) {
      // let { values } = this.$refs.materialTable.getValuesSync({ validate: true, rowIds: [type.row.id] })
      // let { planTotalNum, totalReceivedRemedyNum, lockNum, returnNum } = values[0]
      // console.log(planTotalNum, totalReceivedRemedyNum, lockNum, returnNum)
      // this.$refs.materialTable.setValues([
      //   {
      //     rowKey: type.row.id, // 行的id
      //     values: {
      //       // 在这里 values 中的 amount 是你 columns 中配置的 key
      //       num: integerNum(type.value),
      //     },
      //   },
      // ])
    },
    changeWarranty(v) {
      console.log(v)
      this.$nextTick(() => {
        this.form.setFieldsValue({
          warranty: integerNum(v.target.value),
        })
      })
    },
    selectOrder(v) {
      if (!v) {
        return
      }
      let order = this.orderList.find((item) => item.id == v)
      console.log(order, 'order')
      this.requistionForm.goodsBasicUnitText = order.goodsBasicUnitText
      this.requistionForm.orderCode = order.orderCode
      this.requistionForm.goodsName = order.goodsName
      this.requistionForm.orderId = order.id
      API.messReturnMaterialApplyQueryByOrderId({ orderId: v }).then((res) => {
        if (res.result) {
          for (let i = 0; i < res.result.length; i++) {
            const item = res.result[i]
            res.result[i].num = item.canNum
          }
          this.goodsTable.dataSource = res.result
        }
      })
      console.log(order)
    },
    userFilter(v, row) {
      if (row.length > 0) {
        this.requistionForm.returnerId = row[0].id
      } // this.$refs.ruleForm2.clearValidate('returnerId')
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */

    initForm(querys) {
      this.jkeForm.visible = true
      if (querys && querys.orderId) {
        this.requistionForm.goodsBasicUnitText = querys.goodsBasicUnitText
        this.requistionForm.orderId = querys.orderId
        this.numberValue = querys.orderId
        this.numberText = querys.orderCode
        this.requistionForm.orderCode = querys.orderCode
        this.requistionForm.goodsName = querys.goodsName
        API.messReturnMaterialApplyQueryByOrderId({ orderId: querys.orderId }).then((res) => {
          if (res.result) {
            this.goodsTable.dataSource = res.result
          }
        })
        this.disabled = true
      }
      productOrderList({ pageSize: '999', statusListStr: 'notStarted,inProduction' }).then((res) => {
        if (res.code == 200) {
          this.orderList = res.result.records
        }
      })
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_DEVICE' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            deviceCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 获取附件 */
    getFileList(v) {
      this.requistionForm.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleSubmit(e)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    handleSubmit(processDataVo) {
      let that = this
      that.$refs.ruleForm1.validate((valid) => {
        if (valid) {
          that.$refs.ruleForm2.validate((valid) => {
            if (valid) {
              let { error, values } = that.$refs.materialTable.getValuesSync({
                validate: true,
                rowIds: that.selectRowKeys,
              })
              console.log(error, values)
              if (values.length == 0) {
                that.$antdMessage.error('请先选择物料')
                return
              } else {
                if (error == 0) {
                  that.requistionForm.messPlanMaterialApplyDtoList = values
                  that.requistionForm.processDataVo = processDataVo
                  that.submitLoading = true
                  returnMaterialAdd(that.requistionForm).then((res) => {
                    that.submitLoading = false
                    if (res.code == 200) {
                      that.$antdMessage.success(res.message)
                      that.$emit('refresh')
                      that.goBack()
                    } else {
                      that.$antdMessage.error(res.message)
                    }
                  })
                }
              }
            } else {
              return false
            }
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.item-wrap:nth-of-type(n + 2) {
  margin-top: 40px;
}
.detail-item {
  width: 30%;
}
.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px -40px 24px -40px;
}
.cards-box {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
/deep/ .input-table .tbody .td {
  padding: 14px 8px 14px 8px;
}
</style>
